// 引入 $http 请求对象
import { $http } from '@escook/request-miniprogram'
// 基地址
import baseConfig from './config/index'

import store from '../store/index'

// 将 $http 挂载到 uni 上，方便全局调用
uni.$http = $http

// 配置基地址
uni.$http.baseUrl = baseConfig.baseUrl
uni.$http.timeout = 10000;

// loading相关
let loadingCount = 0
const showLoading = () => {
	uni.showLoading({
		mask: true,
		title: '加载中...'
	})
};
const hideLoading = () => {
	loadingCount -= 1
	if (loadingCount <= 0) {
		setTimeout(() => {
			uni.hideLoading();
		}, 2000)
	}
};

// 请求拦截器
uni.$http.beforeRequest = function(options = { data: {} }) {
  setTimeout(() => {
    if (loadingCount != 0) {
      showLoading()
    }
  }, 1000)
  loadingCount += 1
  if(!options.data?.otherData?.isNoToken){
    const token = store.state.userInfo.token
    if (token) options.header = { Authorization: token }
  }
}

// 响应拦截器
uni.$http.afterRequest = function(res) {
  hideLoading()
  const {statusCode, data } = res
  if(data.code === 401) {
    // store.dispatch('wxLogin')
    // uni.$showMsg('登陆过期')
    // uni.reLaunch({
    //   url: '/pages/login/index'
    // });
    uni.showModal({
      title: '提示',
      content: '请登录后操作',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.reLaunch({
            url: '/pages/newLogin/index'
          });
        }
      }
    })
  } else if (data.code === 403) {
    uni.$showMsg(data.msg)
  } else if(statusCode !== 200 || data.code !== 200) {
    uni.$showMsg(res.data.msg || '接口调用异常')
  }
}

// 往里封装upload相关请求方法
uni.$http.upload = function(url, filePath, formData = {}, name = 'file') {
  return new Promise((resolve, reject) => {
    // 1. 创建基础请求配置
    const token = store.state.userInfo.token
    const options = {
      url: uni.$http.baseUrl + url,
      filePath,
      name,
      formData,
      header: { Authorization: token, isNoToken: true } // 不需要在请求前置再加header
    };
 
    // 2. 触发请求拦截器（动态修改options）
    if (typeof uni.$http.beforeRequest === 'function') {
      uni.$http.beforeRequest(options); // 关键：手动调用拦截器
    }
 
    // 3. 发送请求
    wx.uploadFile({
      ...options, // 使用拦截器修改后的配置
      success(res) {
        const result = {...res, data: JSON.parse(res.data)}
        uni.$http.afterRequest?.(result);
        resolve(result.data)
      },
      fail(err) {
        reject(err);
        hideLoading()
      }
    });
  });
};


uni.$axios = (method = 'get', url = '/', data = {}, otherData = {isNoToken: false}) => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await uni.$http[method](url, {...data, otherData})
      if(!res || res.statusCode !== 200 || res.data.code !== 200) return reject()
      else resolve(res.data)
    } catch(err){
      reject(err)
    }
  })
}

// 封装请求失败提示信息
uni.$showMsg = function(title = '数据加载失败', duration = 1500) {
  uni.showToast({ title, duration, icon: 'none' })
}